package com.itheima.service;

/**
 * @author 芝士雪豹
 * @create 2022/9/18/21:04
 */

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.autoconfig.template.AipFaceTemplate;
import com.itheima.autoconfig.template.HuanXinTemplate;
import com.itheima.autoconfig.template.OssTemplate;
import com.itheima.tanhua.api.db.UserServiceApi;
import com.itheima.tanhua.exception.ConsumerException;
import com.itheima.tanhua.pojo.db.UserInfo;
import com.itheima.tanhua.pojo.db.user;
import com.itheima.tanhua.until.JwtUtils;
import com.itheima.tanhua.until.mongo.Constants;
import io.jsonwebtoken.Claims;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 业务逻辑处理类
 */
@Service
public class UserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @DubboReference //远程调用
    private UserServiceApi userServiceApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    //@Autowired
    //private SmsTemplate smsTemplate;

    /**
     * 发送短信验证 拿前端获取的手机号发
     *
     * @param phone
     */
    public boolean senMsg(String phone) {
        //指定redis存储手机的验证码key
        String redisKey = "CODE_" + phone;
        //redis中是否有验证码
        String redisPhone = stringRedisTemplate.opsForValue().get("phone");
        boolean flag = true;
        if (StrUtil.isNotBlank(redisPhone)) {
            //如果redis还有数据就不再发了
            flag = false;
        } else {
            //int code = RandomUtil.randomInt(6);
            //String code = RandomUtil.randomString(6);
            //方便测试
            String code = "666666";
            //百度云发短信
            //smsTemplate.sendSms(phone,code);
            //把验证码存到redis
            stringRedisTemplate.opsForValue().set(redisKey, code, 3, TimeUnit.MINUTES);
        }
        return flag;
    }

    /**
     * 手机号验证码登录
     *
     * @param pram
     * @return
     */
    public Map loginVerification(Map<String, String> pram) {
        //接收页面传输的手机号和验证码

        String phone = pram.get("phone");
        String code = pram.get("verificationCode");
        //通过手机从redis中获取验证码
        String redisKey = "CODE_" + phone;
        String redisCode = stringRedisTemplate.opsForValue().get(redisKey);
        //比较验证码是否为空
        if (StrUtil.isBlank(redisCode)) {
            //throw new RuntimeException("验证码为空!");
            throw new ConsumerException("验证码为空");
        }
        //比较验证码是否一致
        if (!StrUtil.equals(code, redisCode)) {
            throw new ConsumerException("验证码不一致!");
        }
        user user = userServiceApi.findByPhone(phone);
        //默认是老用户
        boolean isNew = false;
        //判断是否是新用户
        if (ObjectUtil.isNull(user)) {
            //是新用户就创建用户
            user = new user();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            //注册用户
            user.setId(userServiceApi.save(user));
            isNew = true;
            //创建环信用户
            String HxUser = "hx_" + user.getId();
            Boolean created = huanXinTemplate.createUser(HxUser, Constants.INIT_PASSWORD);
            if (created){
                //如果为true就是 环信注册成功 可以添加 绑定用户和环信用户
                user.setHxUser(HxUser);
                user.setPassword(Constants.INIT_PASSWORD);
                userServiceApi.update(user);
            }
        }
        //使用工具类获取token
        String token = JwtUtils.getToken(user.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("isNew", isNew);

        //登录成功需要删除redis
        stringRedisTemplate.delete(redisKey);
        return map;
    }

    /**
     * 头像上传
     *
     * @param token
     * @param headPhoto
     * @throws ConsumerException
     */
    public String upload(String token, MultipartFile headPhoto) {
        //校验token
        boolean b = JwtUtils.verifyToken(token);
        //if (!b){
        //    throw new ConsumerException("token过期!");
        //}
        String url;
        try {
            //调用头像上传功能
            url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        } catch (IOException e) {
            throw new ConsumerException("头像上传失败!");
        }


        boolean detect = aipFaceTemplate.detect(url);
        if (!detect) {
            throw new ConsumerException("头像上传失败!");
        }


        return url;
    }

    /**
     * 完善用户资料
     *
     * @param userInfo
     */
    public void addUserInfo(String token, UserInfo userInfo) {
        boolean b = JwtUtils.verifyToken(token);
        //if (!b){
        //    throw new ConsumerException("token过期了");
        //}
        Long id = JwtUtils.getClaims(token).get("id", Long.class);
        userInfo.setId(id);
        userServiceApi.addUserInfo(userInfo);
    }

    /**
     * 更新头像  滴滴答
     *
     * @param url
     * @param token
     */
    public void addUserAvator(String url, String token) {
        Claims claims = JwtUtils.getClaims(token);
        Long id = claims.get("id", Long.class);
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(url);
        userServiceApi.addUserInfo(userInfo);
    }
}
